package com.github.baichuan.web.valication;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Path;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.groups.Default;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ValidationUtils {
    public final static Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static Map<String, String> message(Errors errors){
        int fieldErrorCount = errors.getFieldErrorCount();
        Map<String, String> map = new HashMap<>(fieldErrorCount);
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for(FieldError error : fieldErrors){
            if(map.containsKey(error.getField())){
                String message = map.get(error.getField()) + ";" + error.getDefaultMessage();
                map.put(error.getField(), message);
            }
            else{
                map.put(error.getField(), error.getDefaultMessage());
            }
        }
        return map;
    }

    public static ValidationResult validate(Object target){
        Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(target, Default.class);
        ValidationResult result = new ValidationResult(target);
        for(ConstraintViolation violation : violations){
            Path path = violation.getPropertyPath();
            result.error(path.toString(), violation.getMessage());
        }
        return result;
    }
}
